/**
 *
 * Copyright (c) 2011 TLOSS. All rights reserved.
 * Created on Apr 22, 2011
 *
 */
package com.tloss.database.db2obj;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.tloss.database.db2obj.classpath.ClassLoaderUtil;
import com.tloss.database.db2obj.classpath.ConfigurationImpl;
import com.tloss.database.db2obj.mysql.MysqlSQLExtractor;
import com.tloss.database.db2obj.utils.AnnotationUtils;
import com.tloss.database.db2obj.utils.DateFormatUtils;
import com.tloss.database.db2obj.utils.NameUtils;

/**
 * @author Tran Tung
 * 
 */
public class Extractor {
	public static void main(String[] args) throws Exception {
		Properties properties = new Properties();
		properties.load(Extractor.class
				.getResourceAsStream("/config.properties"));
		String outputdir = properties.getProperty("outputdir");
		String libdir = properties.getProperty("libdir");
		String _package = properties.getProperty("package");
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass("com.mysql.jdbc.Driver"); // loads the jdbc driver
		cpds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306");
		cpds.setUser("root");
		cpds.setPassword(null);
		cpds.setMinPoolSize(5);
		cpds.setAcquireIncrement(5);
		cpds.setMaxPoolSize(20);
		MysqlSQLExtractor extractor = new MysqlSQLExtractor();
		extractor.setDataSource(cpds);
		extractor.setSchema("jschoolmanager");
		List<Table> tables = extractor.extractTable();
		Properties p = new Properties();
		p.setProperty("resource.loader", "file");
		p.setProperty("file.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		p.setProperty("input.encoding", "UTF-8");
		p.setProperty("output.encoding", "UTF-8");
		VelocityEngine ve = new VelocityEngine();
		ve.init(p);
		/* next, get the Template */
		Template t = ve.getTemplate("/bd2obj.vm");
		/* create a context and add data */
		VelocityContext context = new VelocityContext();
		DateFormatUtils dateFormatUtils = new DateFormatUtils();
		dateFormatUtils.setDate(new Date());
		NameUtils nameUtils = new NameUtils();
		AnnotationUtils annotationUtils = new AnnotationUtils();
		context.put("currentDate", dateFormatUtils);
		context.put("package", _package);
		context.put("typeExtractor", extractor.getTypeExtractor());
		context.put("nameUtils", nameUtils);
		context.put("annotationUtils", annotationUtils);
		
		File file = new File(outputdir);
		if (!file.exists()) {
			file.mkdirs();
		}
		String packageDir = _package.replace('.', File.separatorChar);
		File filePackage = new File(file, packageDir);
		if (!filePackage.exists()) {
			filePackage.mkdirs();
		}
		File lib = new File(libdir);
		if (!lib.exists()) {
			lib.mkdirs();
		}
		List<String> libs = new ArrayList<String>();
		File[] fileLibs = lib.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.isFile() && pathname.getName().endsWith(".jar");
			}
		});
		for (File f : fileLibs) {
			libs.add(f.getAbsolutePath());
		}
		/* now render the template into a FileWriter */
		for (Table table : tables) {
			context.put("table", table);
			FileWriter writer = new FileWriter(new File(filePackage,
					nameUtils.getClassName(table.getName()) + ".java"));
			t.merge(context, writer);
			writer.flush();
			writer.close();
		}
		t = ve.getTemplate("/classpath-project.vm");
		context.put("projectName", properties.getProperty("projectname"));
		context.put("srcdir", file.getAbsoluteFile());
		context.put("libraries", libs);
		context.put("compilerSource", properties.getProperty("compiler.source"));
		context.put("compilerTarget", properties.getProperty("compiler.target"));
		FileWriter writer = new FileWriter(new File(file,"project.xml"));
		t.merge(context, writer);
		writer.flush();
		writer.close();
		ClassLoaderUtil classLoaderUtil =  new ClassLoaderUtil();
		ConfigurationImpl configuration =  new ConfigurationImpl();
		configuration.readConfig(new FileInputStream(new File(file,"project.xml")));
		classLoaderUtil.createAntFile("build.xml", configuration);
		classLoaderUtil.runCompile("build.xml");
		java.lang.ClassLoader current= Thread
				.currentThread().getContextClassLoader();
		java.lang.ClassLoader loader = classLoaderUtil.getClassLoader(current, "build/"
				+ configuration.getProjectName() + ".jar");
		System.out.println(loader);
	}
}
